package pri.damai.xiaowu.auth.security.loginlogic;

import pri.damai.xiaowu.auth.enums.ResultEnum;
import pri.damai.xiaowu.auth.security.loginlogic.base.AbstractLoginLogic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录逻辑工厂类
 * @Desc
 * @Author DaMai
 * @Date 2021/10/13 17:47
 * 但行好事，莫问前程。
 */
@Slf4j
@Component
public class LoginLogicFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    public Map<LoginTypeEnums, AbstractLoginLogic> loginLogicMap = new ConcurrentHashMap<>();

    public AbstractLoginLogic getLoginLogic(LoginTypeEnums value) {
        return Optional.ofNullable(loginLogicMap.get(value)).orElseGet(() -> {
            log.warn("未获取到登录逻辑。logType:{}", value);
            throw new AuthenticationServiceException(ResultEnum.NO_LOGIN_TYPE_LOGIC.desc());
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        applicationContext.getBeansOfType(AbstractLoginLogic.class)
                .values()
                .forEach(loginLogic -> loginLogicMap.put(loginLogic.getSupportLoginType(), loginLogic));
        log.debug("登录逻辑类装载完毕。load login type:{}", loginLogicMap.keySet());
    }
}
